#include <iostream>
#include <string>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include "log.hpp"
#include <sys/socket.h>
#include <ctype.h>
#include <netinet/in.h>
#include <arpa/inet.h>
bool inspectLegalargv(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << "server_ip server_port" << std::endl;
        return false;
    }
    struct sockaddr_in dst;
    bzero(&dst,sizeof(dst));
    int n = inet_pton(AF_INET, argv[1],& dst);
    if (n == 0)
    {
        std::cerr << "invaild network address in the udp address family" << std::endl;
        return false;
    }
    else if (n == -1)
    {
        std::cerr << "invaild network address" << std::endl;
        return false;
    }
    std::string s_port = argv[2];
    for (auto c : s_port)
    {
        if (!isdigit(c))
        {
            std::cerr << "invaild server port" << std::endl;
            return false;
        }
    }
    int port = std::stoi(s_port.c_str());
    if (port >= 0 && port <= 1023)
    {
        std::cerr << "invaild server port(system default port)" << std::endl;
        return false;
    }
    else if (port > 65535)
    {
        std::cerr << "invaild server port" << std::endl;
        return false;
    }
    return true;
}

int main(int argc, char *argv[])
{
    if (!inspectLegalargv(argc, argv))
        return 1;
    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);
    int socketid = socket(AF_INET, SOCK_DGRAM, 0);
    if (socketid < 0)
    {
        std::cerr << "socket fail" << std::endl;
        return 2;
    }
    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());
    server.sin_port = htons(server_port);
    while (true)
    {
        std::string input;
        std::cout << "PLEASE INPUT:";
        std::getline(std::cin, input);
        if (input.size() == 0)
        {
            std::cout << "ILLEGAL INPUT PLEASE INPUT AGAIN" << std::endl;
            continue;
        }
        int n = sendto(socketid, input.c_str(), input.size(), 0, (sockaddr *)&server, sizeof(server));
        if (n == -1)
        {
            std::cerr << "sendto fail" << std::endl;
            return 2;
        }

        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int m = recvfrom(socketid, buffer, sizeof(buffer), 0, (sockaddr *)&peer, &len);
        if (m > 0)
        {
            buffer[m] = 0;
            std::cout << buffer << std::endl;
        }
        else
        {
            MY::LOG(MY::logLevel::DEBUG) << "recvfrom fail";
        }
    }
}